package com.dingding.gmall.ware.listener;

import com.dingding.gmall.common.dto.mq.order.OrderInfoDTO;
import com.dingding.gmall.common.dto.mq.ware.StockLockedSuccessDTO;
import com.dingding.gmall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author liugongding
 * @description:
 * @date 2022/3/29 2:19 PM
 */


@RabbitListener(queues = "stock.release.stock.queue")
@Component
@Slf4j
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockUnlockedRelease(StockLockedSuccessDTO dto, Message message, Channel channel) throws IOException {
        log.info("收到解锁的消息,{}", message);
        //防止关闭订单消息发送延迟导致订单未关闭
        try {
            wareSkuService.unlockStock(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("解锁库存失败,{}", e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderInfoDTO dto, Message message, Channel channel) throws IOException {
        log.info("收到订单关闭的消息,准备解锁库存{}", message);
        try {
            wareSkuService.unlockStock(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
